<template>
	<el-upload
		:action="uploadUrl"
		:headers="uploadHeaders"
		:on-success="handleUploadSuccess"
		:data="uploadParams"
		:accept="uploadAccept"
		:file-list="imageUrlList"
		list-type="picture-card"
		class="lib_cover_Upload"
	>
		<i slot="default" class="el-icon-plus"></i>
		<template slot="file" slot-scope="{ file }">
			<img class="el-upload-list__item-thumbnail" :src="file.url" :alt="file.name" />
			<span class="el-upload-list__item-actions">
				<span class="el-upload-list__item-preview" @click="handleOpenPreview(file)">
					<i class="el-icon-zoom-in"></i>
				</span>
				<span class="el-upload-list__item-delete" @click="handleRemoveCover(file)">
					<i class="el-icon-delete"></i>
				</span>
			</span>
		</template>
	</el-upload>
</template>

<script>
import moment from 'moment';
import { attachDelete } from '@/api/global.js';
export default {
	props: {
		list: {
			type: Array,
			default: () => []
		},
		type: String
	},
	data() {
		return {
			uploadUrl: `${process.env.VUE_APP_BASEURL}tbSysAttachment/upload`,
			uploadHeaders: { Authorization: this.$local.get('token') },
			uploadParams: { type: '5', showType: '1', category: this.type },
			uploadAccept: '.jpg,.jpeg,.png,.gif',
			imageUrlList: []
		};
	},
	mounted() {
		this.imageUrlList = this.list
			.map((item) => {
				return { uid: item.id, name: item.oldName, url: window.staticPath + item.attrAddr, time: moment(item.createTime) };
			})
			.sort((a, b) => {
				return a.time.diff(b.time);
			});
	},
	methods: {
		//上传成功
		handleUploadSuccess(data) {
			console.log(data);
		},

		//删除
		handleRemoveCover(file) {
			let that = this;
			this.$confirm(`此操作将永久删除此封面图, 是否继续?`, '删除提示', {
				type: 'warning',
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						let index = that.imageUrlList.findIndex((item) => item.uid === file.uid);
						instance.confirmButtonLoading = true;
						await that.deleteCoverRequest(file.uid, index);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//删除请求
		async deleteCoverRequest(id, index) {
			let result = await attachDelete(id).then((res) => res.data);
			if (result.code === 0) {
				this.$message.success('删除封面图成功');
				this.imageUrlList.splice(index, 1);
			} else {
				this.$message.error('删除封面图失败');
			}
		},

		//预览
		handleOpenPreview(file) {
			let index = this.imageUrlList.findIndex((item) => item.uid === file.uid);
			this.$emit(
				'preview',
				index,
				this.imageUrlList.map((item) => item.url)
			);
		}
	}
};
</script>

<style lang="scss" scoped>
.lib_cover_Upload::v-deep {
	.el-upload-list__item {
		margin: 0 16px 16px 0;
		width: 138px;
		height: 138px;
		transition: none;
	}
	.el-upload {
		width: 138px;
		height: 138px;
		line-height: 136px;
	}
	.el-upload-list__item-thumbnail {
		object-fit: cover;
	}
}
</style>
